package oss

import (
	"encoding/json"
	"fmt"
	"gitee.com/slclub/aliyun-oss/conf"
	"gitee.com/slclub/aliyun-oss/logq"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"strings"
)

/**
调用AssumeRole获取一个扮演RAM角色的临时身份凭证（STS Token）
AssumeRole
授权：AliyunSTSAssumeRoleAccess

demo
https://sts.aliyuncs.com/?Action=AssumeRole
&DurationSeconds=3600
&RoleArn=acs:ram::1875651988409145:role/xiaoming
&RoleSessionName=alice
*/
func GetStsRoleResponse(role *RoleRAM) *sts.AssumeRoleResponse {
	client, err := sts.NewClientWithAccessKey(conf.Config.OSS.RegionId, conf.Config.OSS.AccessKeyId, conf.Config.OSS.AccessKeySecret)

	//构建请求对象。
	request := sts.CreateAssumeRoleRequest()
	request.Scheme = conf.Config.OSS.Scheme

	//设置参数。关于参数含义和设置方法，请参见《API参考》。
	request.RoleArn = role.RoleArn
	request.RoleSessionName = role.RoleSessionName
	// Policy 可以为空
	if len(role.Policy.Statement) > 0 {
		policy, err := json.Marshal(role.Policy)
		if err != nil {

		}
		request.Policy = string(policy)
	}
	request.DurationSeconds = "3600"

	response, err := client.AssumeRole(request)
	if err != nil {
		fmt.Print(err.Error())
	}
	return response
}

func GetStsSignUrl(method_my HTTP_METHOD, stsInfo *sts.AssumeRoleResponse, object_name string) (string, error) {
	method := oss.HTTPMethod(method_my)
	// 获取STS临时凭证后，您可以通过其中的安全令牌（SecurityToken）和临时访问密钥（AccessKeyId和AccessKeySecret）生成OSSClient。
	endpoint := conf.Config.OSS.UploadEndPoint
	client, err := oss.New(endpoint, stsInfo.Credentials.AccessKeyId, stsInfo.Credentials.AccessKeySecret, oss.SecurityToken(stsInfo.Credentials.SecurityToken))
	if err != nil {
		logq.Error("[STS][SecurityToken]", err)
		fmt.Println("[STS][SecurityToken]ERR:", err)
		return "", err
	}
	// 填写Bucket名称，例如examplebucket。
	bucketName := conf.Config.OSS.Bucket
	// 填写文件完整路径，例如exampledir/exampleobject.txt。文件完整路径中不能包含Bucket名称。
	//objectName := "testdir/exampledir/exampleobject.md"
	// 填写本地文件完整路径，例如D:\\localpath\\examplefile.txt。
	//localFilename := "/Users/yajunxu/tiandi/aliyun/oss/sdk/readme.md"

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		logq.Error("[STS][Bucket]", err)
		fmt.Println("[STS][Bucket]ERROR:", err)
		return "", err
	}

	// 签名直传。
	signedURL, err := bucket.SignURL(object_name, method, 60)
	logq.Info("[STS][UPLOAD_SIGN][SIGN_URL]OK", signedURL)
	fmt.Println("[STS][UPLOAD_SIGN][SIGN_URL]OK", signedURL)
	var val = "QuickUpload"
	err = bucket.PutObjectWithURL(signedURL, strings.NewReader(val))
	// 带可选参数的签名直传。请确保设置的ContentType值与在前端使用时设置的ContentType值一致。
	options := []oss.Option{
		oss.Meta("myprop", "mypropval"),
		oss.ContentType("text/plain"),
	}

	signedURL, err = bucket.SignURL(object_name, method, 60, options...)
	if err != nil {
		logq.Info("[STS][UPLOAD_FILE][SIGN_URL]", signedURL)
		fmt.Println("[STS][UPLOAD_FILE][SIGN_URL]ERROR:", signedURL)
	}

	return signedURL, err
}
